package com.example.a2007dou_shop.fragment

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.a2007dou_shop.entity.CommentEntityResult
import com.example.a2007dou_shop.entity.VideosEntityResult
import com.example.a2007dou_shop.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class VideosViewModel:BaseViewModel() {
    val videoDui = MutableLiveData<VideosEntityResult>()
    val videoCuo = MutableLiveData<String>()
    fun getVideos(page:Int,size:Int){
        viewModelScope.launch {
            try {
                videoDui.value = apiServer.getVideos(page,size)
            }catch (e:Exception){
                videoCuo.value = e.message
            }
        }
    }
    val getCommentDui = MutableLiveData<CommentEntityResult>()
    val getCommentCuo = MutableLiveData<String>()

    fun getComment(videoId:Int){
        viewModelScope.launch {
            try {
                getCommentDui.value = apiServer.getComment(videoId)
            }catch (e:Exception){
                getCommentCuo.value = e.message
            }
        }
    }

    val sendCommentDui = MutableLiveData<CommentEntityResult>()
    val sendCommentCuo = MutableLiveData<String>()

    fun sendComment(videoId:Int,msg:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["videoId"] = videoId
                map["msg"] = msg
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                sendCommentDui.value = apiServer.sendComment(body)
            }catch (e:Exception){
                sendCommentCuo.value = e.message
            }
        }
    }
}